/*
 * Copyright 2010-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.beaut.project.control;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.beaut.project.service.FileUploadService;
import com.beaut.project.util.StaticData;
import com.beaut.project.util.Utility;


@Controller
@RequestMapping("/fileUpload")
public class FileUploadController {

	@Autowired
	private FileUploadService fileUploadService;
	/**
	 * Simply selects the view to render by returning its name.
	 */
	@RequestMapping(value = "/fileupload",method=RequestMethod.POST)
	//swf.js this.ensureDefault("file_post_name", "Filedata");
	public @ResponseBody String fileUpload(@RequestPart("Filedata") MultipartFile request,HttpServletRequest req) {
		String module = req.getParameter("module");
		String save_path = StaticData.UPLOAD_HOME + File.separator + module + File.separator;
		File dir = new File(save_path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String show_name = request.getOriginalFilename();// 用户上传的文件名
		String id = UUID.randomUUID().toString();
		String file_type = show_name.substring(show_name.lastIndexOf("."));// 文件后缀
		
		File file = new File(save_path + id + file_type);
		try {
			request.transferTo(file);// 拷贝文件
			//保存文件信息到数据库
			Map<String,Object> attachemntMap = new HashMap<String,Object>();
			attachemntMap.put("id", id);
			attachemntMap.put("show_name", show_name);
			attachemntMap.put("save_path", save_path);
			attachemntMap.put("file_type", file_type);
			fileUploadService.saveAttachment(attachemntMap);
			
			Map<String, String> map =  new HashMap<String,String>();
			map.put("attachmentId", id);
			map.put("attachmentName", show_name);
			return new String(Utility.rtJson(Utility.RETURN_OK, "上传成功", Utility.toJson(map)).getBytes("utf-8"),"iso-8859-1");
		} catch (IllegalStateException e) {
			e.printStackTrace();
			try {
				return new String(Utility.rtJson(Utility.RETURN_ERROR, "上传出错", null).getBytes("utf-8"),"iso-8859-1");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				return new String(Utility.rtJson(Utility.RETURN_ERROR, "上传出错", null).getBytes("utf-8"),"iso-8859-1");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	@RequestMapping(value="/deleteFile",method=RequestMethod.POST)
	public @ResponseBody String deleteFile(HttpServletRequest request,HttpServletResponse response) {
		String attachmentId = request.getParameter("attachmentId");
		if(!"".equals(attachmentId) && attachmentId!=null){
			Map<String,String> map = fileUploadService.getFileById(attachmentId);
			if(map != null){
				String attachment = map.get("save_path")+map.get("id")+map.get("file_type");
				File file = new File(attachment);
				if(file.exists()){
					file.delete();
					fileUploadService.deleteFileById(attachmentId);
					return "0";
				}
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/downFile")
	 public String downFile(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String attachmentId = request.getParameter("attachmentId");
		if(!"".equals(attachmentId) && attachmentId!=null){
			Map<String,String> map = fileUploadService.getFileById(attachmentId);
			if(map != null){
				OutputStream ops = null;
				String attachment = map.get("save_path")+map.get("id")+map.get("file_type");
			    File file = new File(attachment);
			    if(file.exists()){
			    	InputStream is = new FileInputStream(file);
			    	try {
			    		HashMap<String, String> contentTypeMap = (HashMap<String, String>) fileUploadService.getAttachHeard(map.get("show_name"), null);
			    		String contentTypeDesc = contentTypeMap.get("contentTypeDesc");
			    		//设置html 头信息
			    		
//			      String fName = URLEncoder.encode(attachmentName,"UTF-8");
//			      if (fName.length() > 150) {
//			    	  fName =new String(attachmentName.getBytes("UTF-8") , "ISO-8859-1");
//			      }
//			      fName = fName.replaceAll("\\+", "%20");
			    		response.setHeader("Cache-control","private");
			    		if(contentTypeDesc != null){
			    			response.setContentType(contentTypeDesc);
			    		}else {
			    			response.setContentType("application/octet-stream");
			    		}
			    		response.setHeader("Accept-Ranges","bytes");
			    		response.setHeader("Cache-Control","maxage=3600");
			    		response.setHeader("Pragma","public");
			    		response.setHeader("Accept-Length",String.valueOf(file.length()));
			    		response.setHeader("Content-Length",String.valueOf(file.length()));
			    		response.setHeader("Content-disposition","attachment; filename=\"" + new String(map.get("show_name").getBytes("utf-8"),"iso-8859-1") + "\"");
			    		ops = response.getOutputStream();
			    		if(is != null){
			    			byte[] buff = new byte[8192];
			    			int byteread = 0;
			    			while( (byteread = is.read(buff)) != -1){
			    				ops.write(buff,0,byteread);
			    				ops.flush();
			    			}
			    		}
			    	} catch (Exception ex) {
			    		ex.printStackTrace();
			    		throw ex;
			    	} finally {
			    		if (is != null) {
			    			is.close();
			    		}
			    	}
			    	return null;
			    }
			    else{
			    	return "downloadError";
			    }
			}
		}
		return null;
	 }
}
